//
//  NetWorkTools.swift
//  sinaWeibo
//
//  Created by LiHong on 15/10/28.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import AFNetworking

enum LHNetWorkError: Int {
    case emptyToken = -1
    case emptyuid = -2
    
    var errorDescription: String {
        switch self{
        case .emptyToken: return "token为空"
        case .emptyuid: return "uid为空"
        }
    }
    
    func error() -> NSError {
        return NSError(domain: "cn.itcast.error.net", code: rawValue, userInfo: ["errorDescription" : errorDescription])
    }
}

enum LHNetWorkMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class LHNetWorkTools: NSObject {
    // 属性
    private var afnManneger: AFHTTPSessionManager
    
    // 创建单例
    static let shareInstance: LHNetWorkTools = LHNetWorkTools()
    
    override init() {
        let urlString = "https://api.weibo.com/"
        afnManneger = AFHTTPSessionManager(baseURL: NSURL(string: urlString))
        afnManneger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
    }
    
    // MARK: - OAuth授权
    private let client_id = "290245703"//2391663449   290245703
    private let client_secret = "bf856f993e97fbb0c5f1935b2af1b265" //28c0a970620c0a63fa19c69f95093e83      bf856f993e97fbb0c5f1935b2af1b265
    let redirect_uri = "http://www.baidu.com/"
    
    func oauthURL() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    
    
    //MARK: 获取用户信息
    func loadUserInfo(finish: NetWorkFinishedCallBack) {
        if LHUserAccount.loadAccount()?.access_token == nil{
            print("没有access_token")
            let error = LHNetWorkError.error(LHNetWorkError.emptyToken)
            finish(result: nil, error: error())
            return
        }
        if LHUserAccount.loadAccount()?.uid == nil{
            let error = LHNetWorkError.emptyToken.error()
            finish(result: nil, error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
            "access_token" : LHUserAccount.loadAccount()!.access_token!,
            "uid" : LHUserAccount.loadAccount()!.uid!
        ]
        
        request(LHNetWorkMethod.GET, urlString: urlString, parameters: parameters, finish: finish)
    }
    
    //MARK: - 加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finish: NetWorkFinishedCallBack) {
//        if LHUserAccount.loadAccount()?.access_token == nil{
//            print("access_token为空")
//            let error = LHNetWorkError.emptyToken.error()
//            finish(result: nil, error: error)
//            return
//        }
//        let parameters = [
//            "access_token" : LHUserAccount.loadAccount()!.access_token!
//        ]

        guard var parameters = tokenDict() else{
            // 能进来说明token没有值
            finish(result: nil, error: LHNetWorkError.emptyToken.error())
            return
        }
        
        let urlString = "2/statuses/home_timeline.json"
        
        if since_id > 0 {
            parameters["since_id"] = since_id
        }else if max_id > 0{
            parameters["max_id"] = max_id - 1
        }
        
        request(LHNetWorkMethod.GET, urlString: urlString, parameters: parameters, finish: finish)
    }

    //MARK: - 发微博
    func sendStatus(image: UIImage?, status: String, finish: NetWorkFinishedCallBack) {
        guard var parameters = tokenDict() else{
            // 能进来说明token没有值
            print("LHNetWorkError.emptyToken.error() = \(LHNetWorkError.emptyToken.error())")
            finish(result: nil, error: LHNetWorkError.emptyToken.error())
            return
        }
        
        
        
        parameters["status"] = status
        
        if let img = image {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            afnManneger.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                let data = UIImagePNGRepresentation(img)!
                formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png")
                }, success: { (_, result) -> Void in
                    finish(result: result as? [String: AnyObject] , error: nil)
                }, failure: { (_, error) -> Void in
                    finish(result: nil, error: error)
            })
        } else {
            let urlString = "2/statuses/update.json"
            requestPOST(urlString, parameters: parameters, finish: finish)
        }
        
//        afnManneger.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            finish(result: result as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                finish(result: nil, error: error)
//        }
        
//        afnManneger.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//               // print("result = \(result)")
//            }) { (_, error) -> Void in
//             //   print("error = \(error)")
//        }
    }
    
    
    
    //MARK: - TOKEN
    func tokenDict() -> [String: AnyObject]?{
        if LHUserAccount.loadAccount()?.access_token == nil{
            return nil
        }
        
        return ["access_token" : LHUserAccount.loadAccount()!.access_token!]
    }
    
    //MARK: - 加载授权
    func loadAccessToken(code: String, finish: NetWorkFinishedCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        request(LHNetWorkMethod.POST, urlString: urlString, parameters: parameters, finish: finish)
    }
    
    // 类型别名
    typealias NetWorkFinishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    //MARK: - 封装AFN
    ///封装AFN.GET
    private func requestGET(urlString: String, parameters: AnyObject?, finish: NetWorkFinishedCallBack) {
        afnManneger.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 把结果传出去
            //  print("\(result)")
            finish(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finish(result: nil, error: error)
        }
    }
    
    ///封装AFN.POST
    private func requestPOST(urlString: String, parameters: AnyObject, finish:NetWorkFinishedCallBack){
        afnManneger.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            finish(result: result as? [String : NSObject], error: nil)
            }) { (_, error) -> Void in
                
                finish(result: nil, error: error)
        }
//        afnManneger.POST(urlString, parameters: AnyObject, success: { (<#NSURLSessionDataTask#>, <#AnyObject#>) -> Void in
//            <#code#>
//            }) { (<#NSURLSessionDataTask#>, <#NSError#>) -> Void in
//                <#code#>
//        }
    }
    /// 封装request
    private func request(requestMethod: LHNetWorkMethod, urlString: String, parameters: AnyObject?, finish: NetWorkFinishedCallBack){
        let successCallback = { (_:NSURLSessionDataTask, result: AnyObject) -> Void in
            finish(result: result as? [String: AnyObject], error: nil)
        }
        let failureCallback = { (_:NSURLSessionDataTask, error: NSError) -> Void in
            
            finish(result: nil, error: error)
        }
        switch requestMethod {
        case .GET:
            afnManneger.GET(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        case .POST:
            afnManneger.POST(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        }
    }
}
